package com.technician.exceptionHandler;


import com.technician.common.ResponseResult;
import com.technician.model.enums.HttpStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.List;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(GlobalSystemException.class)
    public ResponseResult<?> globalExceptionHandler(GlobalSystemException e) {
        log.error("globalExceptionHandler", e);
        return ResponseResult.error(e.getCode(), e.getMessage());
    }

    // 权限不足
    @ExceptionHandler(AccessDeniedException.class)
    public ResponseResult<?> runtimeExceptionHandler(AccessDeniedException e) {
        log.error("AccessDeniedException", e);
        return ResponseResult.error(403,"权限不足");
    }

    // 用户名或密码错误
    @ExceptionHandler(InternalAuthenticationServiceException.class)
    public ResponseResult<?> internalAuthenticationServiceExceptionHandler(InternalAuthenticationServiceException e) {
        log.error("InternalAuthenticationServiceException", e);
        return ResponseResult.error(400,"用户名或密码错误");
    }
    @ExceptionHandler(BadCredentialsException.class)
    public ResponseResult<?> badCredentialsExceptionHandler(BadCredentialsException e) {
        log.error("BadCredentialsException", e);
        return ResponseResult.error(400,"用户名或密码错误");
    }

    // 校验异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult<?> runtimeExceptionHandler(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();

        // 存放错误信息
        List<String> errors = new ArrayList<>();
        bindingResult.getFieldErrors().stream().forEach(item->{
            errors.add(item.getDefaultMessage());
        });
        // 将list中的错误信息进行拼接
        String errMessage = StringUtils.join(errors, ",");
        log.error("【系统异常】{}",e.getMessage(),errMessage);
        return ResponseResult.error(400,errMessage);
    }
    @ExceptionHandler(RuntimeException.class)
    public ResponseResult<?> runtimeExceptionHandler(RuntimeException e) {
        log.error("RuntimeException", e);
        return ResponseResult.error(HttpStatusEnum.ERROR_RESPONSE);
    }
}
